#pragma once
#include "err.hpp"
#include "RingQueue.hpp"
#include "LockGuard.hpp"
#include "Thread.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <arpa/inet.h>  // s+truct sockaddr_in
#include <cerrno>
#include <cstring>
#include <strings.h>
#include <cstdlib>
#include <unordered_map>
#include <pthread.h>

// int socket(int domain, int type, int protocal)
// int bind(int sockfd, const struct sockaddr* addr, socklen_t addrlen)

using std::cerr;
using std::cout;
using std::endl;

namespace ns_server
{

    const static uint16_t default_port = 8888;
    using func_t = std::function<std::string(std::string)>;

    class UdpServer
    {
    public:
        UdpServer(/*func_t service,*/ uint16_t port = default_port)
            : /*_service(service),*/ _port(port)
        {
            cout << "Server Port:" << _port << endl;
            pthread_mutex_init(&_mutex, nullptr);

            _p = new Thread(1, std::bind(&UdpServer::Recv, this));
            _c = new Thread(2, std::bind(&UdpServer::Broadcast, this));
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&_mutex);

            _p->join();
            _c->join();
            delete _p;
            delete _c;
        }

        void Start()
        {
            // 1.创建套接字，本质上是打开网络[文件]
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                cerr << "Create socket error: " << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            cout << "Create socket success, fd=" << _sock << endl;

            // 2.给服务器绑定ip,port
            struct sockaddr_in local;
            bzero(&local, sizeof(local)); // 清零
            local.sin_family = AF_INET;
            local.sin_port = htons(_port); // 主机序列转网络序列
            // in_addr_t inet_addr(const char* cp)
            // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 字符串转4字节整数、主机序列转网络序列
            local.sin_addr.s_addr = INADDR_ANY; // 云服务器自动绑定任意ip
            // 绑定
            if (bind(_sock, (struct sockaddr *)&local, sizeof(local)) != 0)
            {
                cerr << "Bind socket error: " << strerror(errno) << endl;
                exit(BIND_ERR);
            }
            cout << "Bind success "
                 << "\n";

            _c->run();
            _p->run();
        }

        // ssize_t recvfrom(int scokfd, void*buf, size_t len,int flags, struct sockaddr* src_addr, socklen_t* addrlen)
        // 返回值是实际读取的长度
        // 后两个参数是让你知道是谁给你发的消息。即客户端的ip+port
        // ssize_t sendto(int sockfd, const void*buf,size_t len,int flags,const struct sockaddr* dest_addr, socklen_t addrlen)
        // void Start()
        // {
        //     char buf[1024];
        //     while (true)
        //     {
        //         // 收消息
        //         struct sockaddr_in peer;
        //         socklen_t len = sizeof(peer); // 这里必须写好大小sizeof(peer)
        //         int n = recvfrom(_sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&peer, &len);
        //         if (n > 0) // 读取成功
        //             buf[n] = '\0';
        //         else
        //             continue; // 继续读取

        //         cout << "[Get a message From " << inet_ntoa(peer.sin_addr) << "-" << ntohs(peer.sin_port) << "]:: " << buf << endl;

        //         // 业务处理
        //         std::string responce = _service(buf);

        //         // 发消息
        //         sendto(_sock, responce.c_str(), responce.size(), 0, (struct sockaddr *)&peer, sizeof(peer));
        //     }
        // }

        void addUser(const std::string &name, const struct sockaddr_in &peer)
        {
            // 在这里修改_onlineuser时线程不安全，加锁保护
            LockGuard lg(&_mutex);
            _onlineuser[name] = peer;
        }

        void Recv()
        {
            char buf[1024];
            while (true)
            {
                // 收消息
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer); // 这里必须写好大小sizeof(peer)
                int n = recvfrom(_sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0) // 读取成功
                    buf[n] = '\0';
                else
                    continue; // 继续读取

                cout << "[Get a message From " << inet_ntoa(peer.sin_addr) << "-" << ntohs(peer.sin_port) << "]:: " << buf << endl;

                // 构建用户信息
                std::string name = inet_ntoa(peer.sin_addr);
                name += "-";
                name += std::to_string(ntohs(peer.sin_port));
                // 添加到用户登录表里
                addUser(name, peer);
                // 生产-添加到环形队列中
                _rq.push(name + ">> " + buf);

                // // 业务处理
                // std::string responce = _service(buf);
            }
        }

        void Broadcast()
        {
            while (true)
            {
                std::string sendstring;
                _rq.pop(&sendstring);
                std::vector<struct sockaddr_in> v;

                { // 加锁保护_onlineuser
                    LockGuard lg(&_mutex);
                    for (auto &user : _onlineuser)
                        v.push_back(user.second);
                }

                for (auto &e : v)
                {
                    sendto(_sock, sendstring.c_str(), sendstring.size(), 0, (struct sockaddr *)&e, sizeof(e));
                }
            }
        }

    private:
        int _sock;      // 文件描述符
        uint16_t _port; // 端口
        // std::string _ip; //云服务器，ip不要了
        // func_t _service; // 业务处理
        std::unordered_map<std::string, struct sockaddr_in> _onlineuser; // 已连接的客户端们
        pthread_mutex_t _mutex;                                          // 保护_onlineuser
        RingQueue<std::string> _rq;                                      // 环形队列
        Thread *_c;
        Thread *_p;
    };
} // end ns_server